<template>
  <view class="navigation">
    <eui-navbar ref="EuiNavBar" title="商品盘点" color="#000000" backgroundColor="#FFFFFF" :storeName="sUserStoreName" :storeId="sUserStore"
                :option="nbOption" @menuFunc="onClickMenuFunc" @onClickStore="clickStore"/>
    <view class="top-view">
      <eui-search-bar ref="RdsSearchBar" v-model="searchText" placeholder="请输入盘点单号、商品条码、编码" leftIcon="icon-saoyisao"
                      @confirm="searchConfirm" @leftIconClick="scanCode" radius="30" :showFilter="true">
        <template v-slot:searchFields>
          <view class="search-fields">
            <eui-card-input v-model="formData.c_count_userno" title="盘点人" @iconClick="clickUser" rightIconType="right"
                            placeholder="请选择盘点人" type="textname2" :displayable="displayable" :name="getName('rdsUsers', formData.c_count_userno)" />
            <eui-card-input v-model="formData.c_status" title="单据状态" placeholder="请选择单据状态"
                            :range="statusList" type="multi" alignType="left" />
            <eui-card-input v-model="formData.c_count_dt_s" title="开始日期" rightIconType="right"
                            placeholder="请选择录入开始日期" type="date" :displayable="displayable" />
            <eui-card-input v-model="formData.c_count_dt_e" title="结束日期" rightIconType="right"
                            placeholder="请选择录入结束日期" type="date" :displayable="displayable" />
            <view class="bottom flex-1 flex">
              <eui-button type="max2" title="重置" singleTag="reset" @buttonClick="confirm"></eui-button>
              <eui-button type="max" title="确认" singleTag="fix" @buttonClick="confirm"></eui-button>
            </view>
          </view>
        </template>
      </eui-search-bar>
    </view>
    <view class="main-view" :style="{ height: listHeight + 'rpx' }">
      <eui-virtual-list @onRefresh="getData" @lower="templateLower" refresher="true" @itemClick="onClickGoToDetail"
                        :origList="dataList" :isBottom="true" :showThirdStatus="true" type="list">
        <template v-slot:list="scope">
          <eui-text title="商品品项数" :value="scope.c_total_item_count" type="number2" />
          <eui-text title="盘盈数量" :value="scope.c_n_p" type="number2" />
          <eui-text title="部门" :value="scope.c_adno" :name="getRelatedName('rdsDeparts', scope.c_adno)" type="titlename2" />
          <eui-text title="盘亏数量" :value="scope.c_n_l" type="number2" />
          <eui-text title="仓库" :value="scope.c_wno" :name="getRelatedName('rdsWnos', scope.c_wno)" type="titlename2" />
          <eui-text title="制单人" :value="scope.c_mk_userno" :name="getRelatedName('rdsUsers', scope.c_mk_userno)" type="titlename2" />
        </template>
        <template v-slot:bottom="scope">
          <view>
            <eui-button :modelValue="scope" type="min" single-tag="confirm" title="盘点录入"
                        :disabled="Number(scope.c_status) >= 4 || Number(scope.c_progress) >= 4"
                        @buttonClick="buttonClick" />
          </view>
        </template>
      </eui-virtual-list>
    </view>
  </view>
</template>

<script setup type="ts">
import dayjs from 'dayjs';
import { ref, reactive, onMounted } from 'vue';
import {useMainStore} from "@/store/modules/store";
import {useLoginStore} from "@/store/modules/useLoginStore";
import { validateStores } from '@/hooks/useValidateMethod';
import {getRdsUrl, rdsRequest} from '@/hooks/rdsServices';
import { getRelatedName, getDictName, getDictSelectList, getDictList } from '../components/RelatedName.js';
import service from "@/common/service";
import dateRangUtil from '../../../common/dateRangUtil';
import {onLoad} from "@dcloudio/uni-app";
import { init } from '@/hooks/init';
import Enjoy from "@/common/enjoy";
import { auditCount } from './app.js'
const mainStore = useMainStore();
const LoginStore = useLoginStore();
const rdsUrl = getRdsUrl();
const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');
const searchText = ref('');
const CurrentPage = ref(1);  //第几页
const PageSize = ref(10);  //每页10条
const RowsCount = ref(0);  //总条数
const PageCount = ref(1);  //总页数
const displayable = ref(false);
const dataList = ref([]);
const c_status = ref('0');
const showRightStyle = ref('text-align: right');
const nbOption = ref({
  items: [
    {title: '新建盘点', onClick: 'onClickNewCount', icon: 'plusempty'},
  ]
})
const formData = ref({
  c_count_dt_s: (dateRangUtil.getLast1Month())[0],
  c_count_dt_e: (dateRangUtil.getLast1Month())[2],
  c_status: '0', // 默认显示未审核
  c_count_userno: '',
}) //查询表单
const sysConfig = ref({
  c_progress: {}, // 盘点进度
  c_status: {}, // 单据状态
});
const statusList = ref([]);
const listHeight = ref(300);  //列表高度
const RdsSearchBar = ref(null);
const EuiNavBar = ref(null);

onLoad(async () => {
  await init();
  await getSysConfig();
  const { loginInfo } = mainStore;
  if (!loginInfo.sUserStore) {
    EuiNavBar.value.onClickStore();
    return;
  }
  await setDefault();
  await getData();
})

// 点击扫描图标跳转打开摄像头
const scanCode = () => {
  uni.scanCode({
    success: function (res) {
      if (res.result != '' && res.result != undefined && res.result != null) {
        searchText.value = res.result;
        getData();
      }
    },
  });
}

// 获取系统参数、字典
const getSysConfig = async () => {
  (await getDictList("盘点进度")).forEach(item => sysConfig.value.c_progress[item.c_id] = item.c_name);
  (await getDictList("PO类单据状态")).forEach(e => {
    sysConfig.value.c_status[e.c_id] = e.c_name;
    statusList.value.push({
      text: e.c_name,
      value: e.c_id,
      checked: formData.value.c_status.includes(e.c_id)
    });
  });
}

const setDefault = async () => {
  const { loginInfo } = mainStore;
  sUserStore.value = loginInfo.sUserStore;
  sUserStoreName.value = loginInfo.sUserStoreName;
  sUser.value = loginInfo.sUser;
}

// 选择框点击事件
const clickStore = () => {
  let parms = Enjoy.GetDialogParms();
  parms.CallBack = SelectionChanged;
  parms.SelectionType = "机构选择";
  parms.SelectedItems = sUserStore.value;
  Enjoy.OpenDialog(parms)
}

// 选择用户
const clickUser = () => {
  let parms = Enjoy.GetDialogParms();
  parms.CallBack = SelectionChangedUser;
  parms.SelectionType = "人员选择";
  parms.SelectedItems = formData.value.c_count_userno;
  Enjoy.OpenDialog(parms)
}

const SelectionChanged = async (event) => {
  if (event.SelectionType == '机构选择') {
    // 更新机构信息
    sUserStoreName.value = event.BackParms.Value;
    sUserStore.value = event.BackParms.Key;
  }
  // 按新条件获取数据
  await getData();
}

const SelectionChangedUser = async (event) => {
  formData.value.c_count_userno = event.BackParms.Key;
}

const getData = async (e) => {
  if (!e) {
    CurrentPage.value = 1;
  }
  service.enjoyShowLoading('正在加载...');
  const req = {
    IsNotPage: false,
    CurrentPage: CurrentPage.value,
    PageSize: PageSize.value,
    UserNo: sUser.value,
    WhereList: [
      {
        c_col: 'c_store_id',
        c_oper: '等于',
        c_value: sUserStore.value,
        c_logic: '而且',
      },
      {
        c_col: 'c_count_dt',
        c_oper: '大于等于',
        c_value: formData.value.c_count_dt_s,
        c_col_dtype: 'System.DateTime',
        c_logic: '而且',
      },
      {
        c_col: 'c_count_dt',
        c_oper: '小于等于',
        c_value: formData.value.c_count_dt_e,
        c_col_dtype: 'System.DateTime',
        c_logic: '而且',
      },
      {
        c_col: 'c_status',
        c_oper: '包含',
        c_value: formData.value.c_status,
        c_logic: '而且',
      },
      {
        c_col: 'c_count_userno',
        c_col_dtype: 'System.String',
        c_left: '',
        c_oper: '=',
        c_logic: '而且',
        c_right: '',
        c_value: formData.value.c_count_userno,
        c_group: '高级',
      },
    ],
  };
  if (searchText.value) {
    // 如果 this.searchText 内容为纯数字
    if (/^\d+$/.test(searchText.value)) {
      req.WhereList.push({
        c_col: "c_gcode",
        c_oper: "等于",
        c_value: searchText.value,
        c_logic: "而且",
      });
    } else {
      req.WhereList = [{
        c_col: 'c_store_id',
        c_oper: '等于',
        c_value: sUserStore.value,
        c_logic: '而且',
      },{
        c_col: 'c_id',
        c_oper: '等于',
        c_value: searchText.value,
        c_logic: '而且',
      }]
    }
  }
  const result = await rdsRequest(rdsUrl.scApi, '商品盘点单', 'EnjoyQueryList', req);
  CurrentPage.value = result.CurrentPage; //第几页
  PageSize.value = result.PageSize; //每页10条
  RowsCount.value = result.RowsCount; //总条数
  PageCount.value = result.PageCount; //总页数
  if (result.CurrentPage == 1) {
    dataList.value = result.ReturnObject;
  } else {
    dataList.value = dataList.value.concat(result.ReturnObject);
  }
  dataList.value.forEach(x => {
    x.c_date = dayjs(x.c_count_dt).format('MM/DD');
  })
  service.enjoyHideLoading();
}

// 上拉加载更多
const templateLower = () => {
  if (CurrentPage.value < PageCount.value) {
    CurrentPage.value = CurrentPage.value + 1;
    getData(true);
  }
}

// 列表项点击跳转到盘点详情页面
const onClickGoToDetail = (e, c_gcode) => {
  let { index, item } = e;
  uni.navigateTo({
    url: './detail?c_id=' + item.c_id + '&c_store_id=' + sUserStore.value + '&c_gcode=' + c_gcode,
  });
}

// 列表项点击跳转到盘点录入页面
const listItemClickInput = (e, c_gcode = '') => {
  // 0-尚未开始、1-初盘、2-复盘、3-三盘、4-预审、5-确认、6-完成
  // c_progress 进度更新 '1' = '初盘/A盘', '2' = '复盘/B盘','3' = '三盘', '9' = '终盘'
  // c_mode2 复盘方式：0-无、1-全部复盘、2-差异复盘、3-AB盘点、4-抽样复盘'
  if ( e.c_progress == '0') {
    auditCount({
      login_store_id: e.c_store_id,
      bill_id: e.c_id,
      oper_type: 'P',
      to_progress: "1",
      is_clear: "0",
      min_sku_rate: "0",
      c_mode2: e.c_mode2,
    }, ()=>{
      getData()
      uni.navigateTo({
        url: './input?c_id=' + e.c_id + '&c_gcode=' + c_gcode + '&c_store_id=' + e.c_store_id,
      });
    })
  } else {
    uni.navigateTo({
      url: './input?c_id=' + e.c_id + '&c_gcode=' + c_gcode + '&c_store_id=' + e.c_store_id,
    });
  }
}

const searchConfirm = async (e) => {
  if (!e) {
    return;
  }
  searchText.value = e.value;
  await getData();
}

const buttonClick = (e) => {
  let { singleTag, modelValue, type } = e;
  switch (singleTag) {
    case 'confirm':
      listItemClickInput(modelValue);
      break;
  }
}

// 新增单据
const onClickMenuFunc = async (e) => {
  switch (e) {
    case 'onClickNewCount':
      setTimeout(() => {
        EuiNavBar.value.closeDrawer();
      },1200);
      // 检查当前机构是否为 分店或配送中心，否则不允许新建
      const result = await validateStores(
          { fieldName: 'c_store_id', newValue: sUserStore.value },
          { ischecklimit: true, firstValueMode: true }
      );
      if (!['2', '3'].includes(result.c_type)) {
        uni.showToast({
          title: '当前机构不允许新建补货单,请切换至分店或配送中心!',
          icon: 'none',
          duration: 3000,
        });
        return;
      }
      uni.navigateTo({
        url: `/pages/RdsViews/StockTaking/plan?storeId=${sUserStore.value}`,
      });
      break;
  }
}

const confirm = (t) => {
  let { singleTag } = t;
  switch (singleTag) {
    case 'reset':
      formData.value.c_count_dt_s = (dateRangUtil.getLast1Month())[0];
      formData.value.c_count_dt_e = (dateRangUtil.getLast1Month())[2];
      formData.value.c_status = '0';
      formData.value.c_count_userno = '';
      statusList.value.forEach(item => item.value == '' ? item.checked = true : item.checked= false)
      break;
    case 'fix':
      getData();
      // 关闭弹出层
      RdsSearchBar.value.closeDrawer();
      break;
  }
}

const getName = (key, value) => {
  if (!value) {
    return ''
  }
  let list = [];
  value.split(',').map(item => {
    list.push("[" + item + "]" + (getRelatedName(key, item) || key));
  })
  return list.join(',');
}

</script>

<style lang="scss" scoped>
@import '../../../main.scss';
.navigation {
  display: flex;
  height: 100vh;
  width: 100%;
  flex-direction: column;
  background: #F2F2F2;
}
.top-view {
  width: 100%;
  height: 88rpx;
  background: #FFFFFF;
  margin-bottom: 20rpx;
}
.main-view {
  flex: 1;
  flex-direction: column;
}
.search-fields {
  width: 100%;
  background: #FFFFFF;
  position: relative;

  .bottom {
    background: #ffffff;
    border-top: 1rpx solid $uni-line-color;
    display: flex;
    justify-content: center;
    padding: 20rpx;
  }
}
</style>
